#!/bin/sh
# nosignal-additions — backend for Settings → Additions (optional software).
# The manifest (additions.json, next to this component's on-system copy) is
# the single source of truth: id/name/desc/icon per item, a `check` command
# (exit 0 = installed) and an `install` command (run in a visible terminal).
#
#   nosignal-additions status        rewrite the status cache (JSON)
#   nosignal-additions list          list manifest items (id<TAB>name)
#   nosignal-additions install <id>  run the item's installer, then re-status
#
# Sources policy: official pacman repos or official upstream installers/git
# only — no AUR, no Flatpak.
set -eu

SHARE="$HOME/.local/share/nosignal/additions-installer"
MANIFEST="${NOSIGNAL_ADDITIONS_MANIFEST:-$SHARE/additions.json}"
STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/nosignal"
STATE="$STATE_DIR/additions-status.json"

[ -f "$MANIFEST" ] || { echo "nosignal-additions: manifest not found: $MANIFEST" >&2; exit 1; }

status() {
  mkdir -p "$STATE_DIR"
  {
    printf '{"checked":"%s","items":[' "$(date -Iseconds)"
    sep=""
    jq -c '.items[]' "$MANIFEST" | while IFS= read -r item; do
      check=$(printf '%s' "$item" | jq -r '.check')
      if sh -c "$check" >/dev/null 2>&1; then inst=true; else inst=false; fi
      printf '%s' "$sep"
      printf '%s' "$item" | jq -c --argjson inst "$inst" 'del(.check, .install) + {installed: $inst}'
      sep=","
    done
    printf ']}\n'
  } > "$STATE.tmp"
  jq -e . "$STATE.tmp" >/dev/null    # never replace the cache with broken JSON
  mv "$STATE.tmp" "$STATE"
}

install_one() {
  id="$1"
  item=$(jq -ce --arg id "$id" '.items[] | select(.id == $id)' "$MANIFEST") \
    || { echo "nosignal-additions: unknown addition: $id" >&2; exit 1; }
  name=$(printf '%s' "$item" | jq -r '.name')
  cmd=$(printf '%s' "$item" | jq -r '.install')
  printf '\033[1;34m::\033[0m installing %s\n' "$name"
  sh -ec "$cmd"
  printf '\033[1;34m::\033[0m %s — installer finished\n' "$name"
  status
}

case "${1:-}" in
  status)  status ;;
  list)    jq -r '.items[] | "\(.id)\t\(.name)"' "$MANIFEST" ;;
  install) [ -n "${2:-}" ] || { echo "usage: nosignal-additions install <id>" >&2; exit 2; }
           install_one "$2" ;;
  *)       echo "usage: nosignal-additions status | list | install <id>" >&2; exit 2 ;;
esac
